#include "url.h"
#include "string.h"
#include "log.h"
#include "assert.h"

void get_url_md5(url_t& url_, md5& md5_,  md5_t& md5_t_)
{
	md5_.generate((unsigned char*)url_.szurl, strlen(url_.szurl));
	md5_.getmd5_t(md5_t_);
}

void copy_url(url_t* src, url_t* dst)
{
	memset(dst->szurl, 0, sizeof(dst->szurl));
	memcpy(dst->szurl, src->szurl, strlen(src->szurl));
}


int copy_allhost(url_t* url, char* host, int len)
{
	if(url == 0 || host == 0 || len < URL_LEN-1)
		return -1;
	char* dot = strchr(url->szurl, '.');
	if( dot == 0)	return -1;
	char* slash = strchr(dot, '/');
	if( slash == 0)
	{
		strcpy(host, url->szurl);	
	}
	else
	{
		memcpy(host, url->szurl, (int)(slash - url->szurl));
	}
	return -1;
}

int filter_url(char*& szurl, int& len)
{
	if( szurl == 0 || len > URL_LEN-1)
		return -1;
	eURL_TYPE eurl_type = eURL_UNKNOWN;
	if( strstr(szurl, "http://") == szurl)
	{
		eurl_type = eURL_HTTP;
		szurl += 7; len -= 7;//http://
	}
	else if( strstr(szurl, "://") 	== 0 ||
	         strstr(szurl, "://")  > szurl + 7) // http:// 
	{
		//no url, such as www.abc.com
		// or www.abc.com/asp?url=http://www.bbb.com
		eurl_type = eURL_HTTP; 
	}
	return eurl_type == eURL_HTTP;
}
/*
int put_url(url_t* url, char* szurl, int len)
{
	if( url == 0 || szurl == 0 || len > URL_LEN-1)
		return -1;
	if(!filter_url(szurl, len))
	{
		if(url)
			release_url(url);
		return -1;
	}
	memcpy(url->szurl, szurl, len);//dont use strcpy
	return 0;
}
*/
url_t* create_url(const char* szurl, int len)
{
	if( szurl == 0 || len >= URL_LEN)
		return 0;
	url_t* url = new url_t;
	memset(url->szurl, 0, sizeof(url->szurl));
	strcpy(url->szurl, szurl);
	return url;
}
url_t* create_url(url_t* url)
{
	assert(url != 0 && url->szurl != NULL && strlen(url->szurl)!=0);
	return create_url(url->szurl, strlen(url->szurl));
}
void del_url(url_t* url)
{
	delete url;
}

int release_url(void* data)
{
	if( data == NULL)
		return -1;
	url_t* url = (url_t*)data;
	del_url(url);
	return 0;
}

